const { createApp, ref, onMounted, computed } = Vue;
const { RefreshLeft } = ElementPlus;
// Define the BookmarkItem component
// Define the BookmarkItem component
const BookmarkItem = {
	name: "BookmarkItem",
	props: {
		item: Object,
	},
	setup(props, { emit }) {
		const isOpen = ref(false);

		const toggleOpen = () => {
			isOpen.value = !isOpen.value;
		};

		const handleRemove = () => {
			emit("remove", props.item);
		};

		const handleNavigate = () => {
			emit("navigate", props.item);
		};

		return {
			isOpen,
			toggleOpen,
			handleRemove,
			handleNavigate,
		};
	},
	template: `
      <div style="display: flex;flex-direction: column;cursor: pointer;">
          <button v-if="item.tag"  @click="toggleOpen">
              <span>{{ item.tag }}</span>
              <svg v-if="!isOpen" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M7 10l5-5H2l5 5z" stroke="#555" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              <svg v-if="isOpen" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M10 7l-5 5-5-5h10z" stroke="#555" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
          </button>
          <div v-if="item.children && isOpen" class="folder-contents">
              <bookmark-item 
                  v-for="(child, index) in item.children" 
                  :key="index" 
                  :item="child"
                  @remove="handleRemove"
                  @navigate="$emit('navigate', $event)">
              </bookmark-item>
          </div>
          <button v-if="!item.children" @click="handleNavigate">{{ item.name }}</button>
      </div>
  `,
};
const app = createApp({
	components: {
		"bookmark-item": BookmarkItem,
	},
	setup() {
		const tabs = ref([{ title: "百度", url: "https://www.baidu.com" }]);
		const activeTab = ref(0);
		const currentUrl = ref("https://www.baidu.com");
		const addressBar = ref("https://www.baidu.com");
		const bookmarks = ref([]);
		const treeData = ref([]);
		const showDialog = ref(false);
		const bookmarkTitle = ref("");
		const bookmarkUrl = ref("");
		const selectedFolderPath = ref("");
		const folderOptions = computed(() => {
			const options = [];
			const traverse = (item, path = "") => {
				if (item.tag) {
					const newPath = path ? `${path}/${item.tag}` : item.tag;
					options.push({ path: newPath, label: newPath });
					for (const child of item.children) {
						traverse(child, newPath);
					}
				}
			};
			if (bookmarks.value && Array.isArray(bookmarks.value)) {
				for (const item of bookmarks.value) {
					traverse(item);
				}
			}
			options.unshift({ path: "", label: "根目录" });
			return options;
		});

		const fetchData = async () => {
			const response = await axios.get("api/bookmarks.json");
			return response.data;
		};

		const addBookmark = () => {
			const newBookmark = {
				name: bookmarkTitle.value,
				url: bookmarkUrl.value,
			};
			let [a, b] = selectedFolderPath.value.split("/");
			function tag(bMs, floor = false) {
				bMs.forEach(item => {
					if (item.tag) {
						if (item.tag == selectedFolderPath.value && !floor) {
							item.children.push(newBookmark);
						} else {
							tag(item.children);
						}
						if (floor && a == item.tag) {
							item.children.forEach(ele => {
								if (ele.tag == b) {
									ele.children.push(newBookmark);
								}
							});
						}
					}
				});
			}
			if (selectedFolderPath.value)
				selectedFolderPath.value.includes("/")
					? tag(bookmarks.value, (floor = true))
					: tag(bookmarks.value);
			else {
				bookmarks.value.push(newBookmark);
			}
			closeDialog();
			treeData.value = convertBookmarksToTreeData(bookmarks.value);
		};

		const addTab = () => {
			tabs.value.push({ title: "百度", url: "https://www.baidu.com" });
			switchTab(tabs.value.length - 1);
		};

		const closeTab = index => {
			tabs.value.splice(index, 1);
			if (activeTab.value === index && tabs.value.length > 0) {
				switchTab(Math.min(index, tabs.value.length - 1));
			} else if (tabs.value.length === 0) {
				addTab();
			}
		};

		const switchTab = index => {
			let i = index;
			if (i >= tabs.value.length) {
				i = 0;
			}
			activeTab.value = i;
			currentUrl.value = tabs.value[i].url;
			addressBar.value = currentUrl.value;
		};

		const goBack = () => {
			// Logic for going back in history
		};

		const goForward = () => {
			// Logic for going forward in history
		};

		const refresh = () => {
			// Refresh
		};

		const navigate = () => {
			currentUrl.value = addressBar.value;
		};

		const openBookmarkDialog = () => {
			bookmarkUrl.value = currentUrl.value;
			bookmarkTitle.value = tabs.value[activeTab.value].title;
			showDialog.value = true;
		};

		const closeDialog = () => {
			showDialog.value = false;
			bookmarkTitle.value = "";
			bookmarkUrl.value = "";
			selectedFolderPath.value = "";
		};

		const navigateToBookmark = bookmark => {
			tabs.value.push({ title: bookmark.name, url: bookmark.url });
			switchTab(tabs.value.length - 1);
		};

		const convertBookmarksToTreeData = bookmarks => {
			const treeData = [];
			bookmarks.forEach(item => {
				if (!item.name) {
					treeData.push({
						label: item.tag,
						children: convertBookmarksToTreeData(item.children),
					});
				} else {
					treeData.push({
						label: item.name,
						url: item.url,
						children: [],
					});
				}
			});
			return treeData;
		};

		const allowDrop = (draggingNode, dropNode, type) => {
			// 如果拖动的是书签（有 URL），仅允许放入文件夹（内嵌）
			if (dropNode.data.url && type === "inner") {
				return false;
			}
			return true;
		};

		const handleNodeDrop = (draggingNode, dropNode, dropType) => {
			function f(datas) {
				let res = [];
				datas.forEach(data => {
					if (data.children.length) {
						res.push({
							tag: data.label,
							children: f(data.children),
						});
					} else {
						res.push({
							name: data.label,
							url: data.url,
						});
					}
				});
				return res;
			}
			bookmarks.value = f(treeData.value);
		};

		onMounted(() => {
			fetchData().then(data => {
				bookmarks.value = data;
				treeData.value = convertBookmarksToTreeData(data);
			});
		});

		return {
			tabs,
			activeTab,
			currentUrl,
			addressBar,
			bookmarks,
			treeData,
			showDialog,
			bookmarkTitle,
			bookmarkUrl,
			selectedFolderPath,
			folderOptions,
			fetchData,
			addBookmark,
			addTab,
			closeTab,
			switchTab,
			goBack,
			goForward,
			refresh,
			navigate,
			openBookmarkDialog,
			closeDialog,
			navigateToBookmark,
			convertBookmarksToTreeData,
			allowDrop,
			handleNodeDrop,
		};
	},
});
const vm = app.use(ElementPlus).mount("#app");
